package com.drinks.yiniang.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.IntDef;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.common.listener.OnCountChangeListener;
import com.drinks.yiniang.entity.event.ShopCartEvent;
import com.drinks.yiniang.entity.goods.GoodsDetailJson;
import com.drinks.yiniang.entity.goods.GoodsObject;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.user.order.OrderConfirmActivity;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.drinks.yiniang.ui.widget.layout.NumCounterLayout;
import com.hansen.library.Constants;
import com.hansen.library.listener.CheckDoubleClickListener;
import com.hansen.library.ui.widget.dialog.BaseDialogFragment;
import com.hansen.library.ui.widget.layout.AutoLineFeedLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;

/**
 * @author han
 * @date 2019/11/8
 */
public class AddToCartDialog extends BaseDialogFragment implements View.OnClickListener, View.OnTouchListener, OnCountChangeListener {

    public static final int TYPE_ADD_TO_CART_DEFAULT = 0x01;//默认操作
    public static final int TYPE_ADD_TO_CART_ADD = 0x02;//加入购物车操作
    public static final int TYPE_ADD_TO_CART_BUY = 0x03;//购买操作

    private Dialog mDialog;

    //封面
    private RatioRoundImageView iv_cart_dialog_cover;
    //关闭
    private ImageView iv_cart_dialog_close;

    //商品名称
    private TextView tv_cart_dialog_goods_name;
    //当前选择的属性
    private TextView tv_cart_dialog_selected_attrs;
    //价格
    private TextView tv_cart_dialog_price;
    //属性名称
    private TextView tv_cart_dialog_attrs_name;
    private AutoLineFeedLayout ll_cart_dialog_goods_attrs;
    //购买数量
    private NumCounterLayout ll_cart_dialog_counter;
    //加入购物车
    private Button btn_cart_dialog_add;
    //立即购买
    private Button btn_cart_dialog_buy;

    @AddToCartDialogTypeDef
    private int mDialogType = TYPE_ADD_TO_CART_ADD;

    @IntDef({
            TYPE_ADD_TO_CART_DEFAULT,
            TYPE_ADD_TO_CART_ADD,
            TYPE_ADD_TO_CART_BUY
    }) //限定为 FlagContants.OK, FlagContants.ERROR
    @Target({
            ElementType.PARAMETER,
            ElementType.FIELD,
            ElementType.METHOD,
    }) //表示注解作用范围，参数注解，成员注解，方法注解
    @Retention(RetentionPolicy.SOURCE) //表示注解所存活的时间,在运行时,而不会存在 .class 文件中
    public @interface AddToCartDialogTypeDef { //接口，定义新的注解类型
    }

    private OnAddToCartClickListener onAddToCartClickListener;

    private List<TextView> mAttrsTextViewList;

    private GoodsObject mGoodsObject;

    private int dp5;
    private int dp10;
    //数量
    private int mSelectNum;
    //选择sku属性id
    private String mSelectAttrsId;

    public static AddToCartDialog newInstance(GoodsObject data, @AddToCartDialogTypeDef int type) {

        AddToCartDialog dialog = new AddToCartDialog();

        Bundle args = new Bundle();

        //商品详情
        args.putSerializable(Constants.KeyObject, data);
        args.putInt(Constants.KeyType, type);

        dialog.setArguments(args);

        return dialog;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            onAddToCartClickListener = (OnAddToCartClickListener) context;
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + " must implement OnAddToCartClickListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 定义Dialog布局和参数
        mDialog = new Dialog(getActivity(), R.style.AddCartDialogStyle);

        // 获取Dialog布局
        View mView = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_add_to_cart, null);

        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        mDialog.setContentView(mView);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);

        Window dialogWindow = mDialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        iv_cart_dialog_cover = mView.findViewById(R.id.iv_cart_dialog_cover);
        iv_cart_dialog_close = mView.findViewById(R.id.iv_cart_dialog_close);

        tv_cart_dialog_goods_name = mView.findViewById(R.id.tv_cart_dialog_goods_name);
        tv_cart_dialog_selected_attrs = mView.findViewById(R.id.tv_cart_dialog_selected_attrs);
        tv_cart_dialog_price = mView.findViewById(R.id.tv_cart_dialog_price);
        tv_cart_dialog_attrs_name = mView.findViewById(R.id.tv_cart_dialog_attrs_name);

        ll_cart_dialog_goods_attrs = mView.findViewById(R.id.ll_cart_dialog_goods_attrs);

        ll_cart_dialog_counter = mView.findViewById(R.id.ll_cart_dialog_counter);

        btn_cart_dialog_add = mView.findViewById(R.id.btn_cart_dialog_add);
        btn_cart_dialog_buy = mView.findViewById(R.id.btn_cart_dialog_buy);

        iv_cart_dialog_close.setOnClickListener(this);

        btn_cart_dialog_add.setOnClickListener(this);
        btn_cart_dialog_buy.setOnClickListener(this);

        ll_cart_dialog_counter.setOnCountChangeListener(this);

        initData();

        mDialog.getWindow().getDecorView()
                .setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent event) {
                        InputMethodManager manager = (InputMethodManager) getActivity()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (event.getAction() == MotionEvent.ACTION_DOWN) {
                            if (getDialog().getCurrentFocus() != null
                                    && getDialog().getCurrentFocus().getWindowToken() != null) {
                                manager.hideSoftInputFromWindow(
                                        getDialog().getCurrentFocus().getWindowToken(),
                                        InputMethodManager.HIDE_NOT_ALWAYS);
                            }
                        }
                        return false;
                    }
                });

        return mDialog;
    }

    private void initData() {
        mContext = getActivity();

        dp5 = ScreenSizeUtils.dp2px(mContext, 5);
        dp10 = ScreenSizeUtils.dp2px(mContext, 10);

        mSelectNum = ll_cart_dialog_counter.getTextCount();

        if (getArguments() != null) {
            mGoodsObject = (GoodsObject) getArguments().getSerializable(Constants.KeyObject);
            mDialogType = getArguments().getInt(Constants.KeyType, TYPE_ADD_TO_CART_DEFAULT);
        }

        if (mDialogType == TYPE_ADD_TO_CART_ADD) {
            btn_cart_dialog_add.setVisibility(View.VISIBLE);
            btn_cart_dialog_buy.setVisibility(View.GONE);
        } else if (mDialogType == TYPE_ADD_TO_CART_BUY) {
            btn_cart_dialog_add.setVisibility(View.GONE);
            btn_cart_dialog_buy.setVisibility(View.VISIBLE);
        } else {
            btn_cart_dialog_add.setVisibility(View.VISIBLE);
            btn_cart_dialog_buy.setVisibility(View.VISIBLE);
        }

        setGoodsData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cart_dialog_close://关闭
                dismiss();
                break;
            case R.id.btn_cart_dialog_add://加入购物车
                addToCart();
                break;
            case R.id.btn_cart_dialog_buy://立即购买
                doBuyNow();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (ll_cart_dialog_counter.getEditTextView() != null && ll_cart_dialog_counter.getEditTextView().getWindowToken() != null) {
                if (isShouldHideKeyBoard(ll_cart_dialog_counter.getEditTextView(), event)) {
                    hideKeyboard(ll_cart_dialog_counter.getEditTextView().getWindowToken());
                }
            }
        }

        return true;
    }

    @Override
    public void onMinusCount(int count) {
        mSelectNum = count;
    }

    @Override
    public void onPlusCount(int count) {
        mSelectNum = count;
    }

    private boolean judgeParams() {
        if (mGoodsObject == null || StringUtils.isEmpty(mGoodsObject.getId())) {
            ToastUtils.showShort(getString(R.string.text_the_goods_does_not_exist));
            return false;
        }

        if (!CommonUtils.isEmptyList(mAttrsTextViewList)) {
            for (int i = 0; i < mAttrsTextViewList.size(); i++) {
                if (mAttrsTextViewList.get(i).isSelected()) {
                    mSelectAttrsId = (String) mAttrsTextViewList.get(i).getTag(R.id.key_tag_id);
                    break;
                }
            }

            if (StringUtils.isEmpty(mSelectAttrsId)) {
                ToastUtils.showShort(getString(R.string.text_please_select) + StringUtils.getTextViewString(tv_cart_dialog_attrs_name.getText()));
                return false;
            }
        }

        return true;
    }

    //立即购买
    private void doBuyNow() {
        if (!judgeParams()) {
            return;
        }

        if (onAddToCartClickListener != null) {
            onAddToCartClickListener.onAddToCartBuyClick(mSelectAttrsId, mSelectNum);
        }

        Intent intent = new Intent(mContext, OrderConfirmActivity.class);
        intent.putExtra(Constants.KeyGoodsId, mGoodsObject.getId());
        intent.putExtra(Constants.KeyNubmer, mSelectNum);
        intent.putExtra(Constants.KeySkuId, mSelectAttrsId);

        startActivity(intent);

        dismiss();
    }

    //加入购物车
    private void addToCart() {
        if (!judgeParams()) {
            return;
        }

        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(mGoodsObject.getId(), mSelectAttrsId, mSelectNum, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));

                if (onAddToCartClickListener != null) {
                    onAddToCartClickListener.onAddToCartAddClick(mSelectAttrsId, mSelectNum);
                }
                dismiss();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //设置商品信息
    private void setGoodsData() {
        if (mGoodsObject == null) {
            return;
        }

        GlideUtils.loadSquareImage(mContext, iv_cart_dialog_cover, mGoodsObject.getCoverUrl());
        tv_cart_dialog_goods_name.setText(mGoodsObject.getName());
        tv_cart_dialog_price.setText("¥" + StringUtils.getNullEmptyConvert__(mGoodsObject.getApp_price()));

        addGoodsAttrs(mGoodsObject.getSku());
    }

    //添加sku属性
    public void addGoodsAttrs(List<GoodsDetailJson.GoodsDetailSku> attrsList) {
        if (CommonUtils.isEmptyList(attrsList)) {
            return;
        }

        tv_cart_dialog_attrs_name.setText(attrsList.get(0).getName());

        if (mAttrsTextViewList == null) {
            mAttrsTextViewList = new ArrayList<>();
        }

        mAttrsTextViewList.clear();
        ll_cart_dialog_goods_attrs.removeAllViews();

        LinearLayout.LayoutParams paramsAttrsValue = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        //动态添加属性值
        for (int i = 0; i < attrsList.size(); i++) {
            final AppCompatTextView tvAttrsValueView = getAttrsTextView();

            tvAttrsValueView.setText(attrsList.get(i).getName());
            tvAttrsValueView.setTag(R.id.key_tag_id, attrsList.get(i).getId());

            //属性值点击
            tvAttrsValueView.setOnClickListener(new CheckDoubleClickListener() {
                @Override
                public void onCheckDoubleClick(View v) {
                    switchAttrsChecked((TextView) v);
                }
            });

            mAttrsTextViewList.add(tvAttrsValueView);

            ll_cart_dialog_goods_attrs.addView(tvAttrsValueView, paramsAttrsValue);
        }
    }

    //切换sku选择状态
    private void switchAttrsChecked(TextView tvAttrsValue) {
        if (CommonUtils.isEmptyList(mAttrsTextViewList)) {
            return;
        }

        for (int i = 0; i < mAttrsTextViewList.size(); i++) {
            if (mAttrsTextViewList.get(i) != tvAttrsValue) {
                mAttrsTextViewList.get(i).setSelected(false);
            }
        }

        tvAttrsValue.setSelected(!tvAttrsValue.isSelected());

        if (tvAttrsValue.isSelected()) {
            tv_cart_dialog_selected_attrs.setText(getString(R.string.text_already_selected_colon) + StringUtils.getTextViewString(tvAttrsValue.getText()));
        } else {
            tv_cart_dialog_selected_attrs.setText(getString(R.string.text_already_selected_colon) + "--");
        }
    }

    private AppCompatTextView getAttrsTextView() {
        AppCompatTextView tvAttrsValue = new AppCompatTextView(mContext);

        tvAttrsValue.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.color_goods_attrs_value));
        tvAttrsValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        tvAttrsValue.setBackgroundResource(R.drawable.selector_goods_attrs);
        tvAttrsValue.setPadding(dp10, dp5, dp10, dp5);
        tvAttrsValue.setClickable(true);
        tvAttrsValue.setSelected(false);
        tvAttrsValue.setEnabled(true);

        return tvAttrsValue;
    }

    @Override
    public void dismiss() {
        View view = getDialog().getCurrentFocus();
        if (view instanceof TextView) {
            hideKeyboard(view.getWindowToken());
        }
        super.dismiss();
    }

    @Override
    public void onDestroy() {
        mDialog = null;
        onAddToCartClickListener = null;
        mSelectAttrsId = null;
        super.onDestroy();
    }

    public interface OnAddToCartClickListener {
        void onAddToCartAddClick(String attrs, int count);

        void onAddToCartBuyClick(String attrs, int count);
    }
}
